﻿//*************************************************************************
//面向服务的协作式智能交通系统仿真软件SoC-ITSS v2.1 alpha
//发布单位：西北工业大学--巴黎高科MINES机器人与群智能系统联合实验室
//团队负责人：张凯龙 Zhang Kailong
//团队成员：张大方、杨安胜、王敏、谢策、王雨佳、谢尘玉等
//联系我们：kl.zhang@nwpu.edu.cn
//2012-2021
//*************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using CyberCarSimulation.Bean;
using CyberCarSimulation.RoadModel;
using CyberCarSimulation.Regulation;
using CyberCarSimulation.Simulation;

//*******************************************************
//
//文件名(File Name):           FIFOMultiQueue_Sche.cs
//
//数据表(Tables):              nothing 
//
//          修改理由：         基于先来先服务的多队列调度 FIFO-MQ
//
//*******************************************************

namespace CyberCarSimulation.Algorithm
{
    //SuperVehicleManager对象描述了一辆车在通过路口的过程中对S-CS资源的全部需求
    //每个SuperVehicleManager对象中包含若干个VehicleManger对象，
    class FIFOMultiQueue_Sche
    {
        private string ID;          //Agent的ID,此ID与路口ID相同
        private int IDNum;          //第几个Agent的Num号
        private int MaxAuthNum;     //最大授权
        private int MsgCount = 0;   //发送至车辆的消息数量

        /************************************************************************/
        /* 发出申请消息之后的车辆的数据信息                                                                     */
        /************************************************************************/
        //键值对，用于存储申请该临界区的车辆的VehicleManager信息，取用方式为<车辆的ID，车辆对应的CS消息>，其中每一条队列既是一个临界区所对应的CS消息
        private List<KeyValuePair<string, VehicleManager>>[] CS = new List<KeyValuePair<string, VehicleManager>>[5];
        //各车道的队列，存储各车道申请临界区的车辆的SuperVehicleManager信息，对应于4个车道
        private List<SuperVehicleManager>[] LaneQueue = new List<SuperVehicleManager>[5];

        /************************************************************************/
        /* 当前已授权车辆的信息，此处只存储其车辆和临界区消息，不存储具体的消息  */
        /************************************************************************/
        //键值对，<CSID，ID>用于记录将编号为CSID的S-CS资源授权给编号为ID的车辆,其数目最多为4 ，对应于4个临界区
        public Dictionary<int, List<string>> Authorize_CS_to_Vehicle = new Dictionary<int, List<string>>();
        //保存当前被授权的车辆ID号，  其数量最多为4，代表一个时间段之内最多只有4辆车被授权
        private List<string> Authorized_Vehicle_Sequence = new List<string>();
        //保存之前已经被授权完成的车辆这些车辆无需再被授权
        private List<string> Already_Authorized_All_CS_Vehicles = new List<string>();

        //Token[XXX]为true表示编号为XXX的S-CS资源已经被占用，为false则表示该资源空闲
        private int[] Token = new int[5];

        //用于分辨是否会产生死锁
        private bool[] Walked = new bool[5];
        private bool[,] SourceGraph = new bool[5, 5];

        //用于多车授权时，标记 N辆车所需要的临界区   false代表不需要 true代表需要
        private bool[] IsAuth = new bool[5];

        /************************************************************************/
        /* 初始化                                                                     */
        /************************************************************************/
        public FIFOMultiQueue_Sche(string ID)
        {
            //设置ID
            this.ID = ID;
            this.IDNum = int.Parse(ID.Substring(3, 2));


            for (int i = 0; i < 5; i++)
            {
                this.Token[i] = 0;   //为false则表示该临界区资源空闲
                this.CS[i] = new List<KeyValuePair<string, VehicleManager>>();
                this.LaneQueue[i] = new List<SuperVehicleManager>();
                this.IsAuth[i] = false;
            }
        }

        /************************************************************************/
        /* MultiSCSFIFO_Sche对象的对外接口，用于执行FIFO调度算法                */
        /************************************************************************/
        public void executeAlgorithm(Intersection Intersection,int AuthNum)
        {
            this.MaxAuthNum = AuthNum * 4;

            //读入消息
            this.readMessageFromVehicle(Intersection);
            //对临界区进行分配
            this.processLeftVehicles(Intersection);

            for (int i = 0; i < 5; ++i)
            {
                for (int j = 0; j < this.CS[i].Count; ++j)
                {
                    this.CS[i].ElementAt(j).Value.isSelect = false;
                }
            }

            
        }

        /************************************************************************/
        /* 从Msg_Buffer类的存储空间中读取相关信息，如Msg_Reservation消息、Msg_Release消息等。*/
        /************************************************************************/
        private void readMessageFromVehicle(Intersection Intersection)
        {
            //获取路口中的消息队列
            List<Message> VtoA_BufferTemp = Intersection.GetVtoA_Buffer();    //局部变量，需要重新写回去
            
            while (VtoA_BufferTemp.Count != 0)
            {

                //取出一条Message
                Message m = VtoA_BufferTemp.ElementAt(0);
                VtoA_BufferTemp.Remove(m);
                
                switch (m.GetType())
                {
                    //在预约消息下需要创建新消息，并将消息存入不同的队列中
                    case Definitions.MsgReservation:
                        SuperVehicleManager vm;

                        string LaneIDTemp = m.GetLaneIDStr();
                        
                        
                        vm = new SuperVehicleManager(m.GetSender(),int.Parse(LaneIDTemp.Substring(5, 1)), m.GetTsArray(), m.GetTeArray(),
                                            m.GetTotal_Dis(), m.GetSectionID(), m.GetPriority());
                        /*将生成的车辆管理实体加入到对应的队列中*/
                        //因为进入车道的车辆本身具有具有顺序，所以此处无需对车道按照车辆插入时间对车辆进行排序
                        this.LaneQueue[vm.LaneID].Add(vm);
                        this.updateCSQueue(vm);
                        this.sortCSQueue();
                        break;
                    case Definitions.MsgFault:              //车辆故障信息
                        break;
                    case Definitions.MsgWait:               //等待临界区消息
                        break;
                    case Definitions.MsgRenew:             //更新状态消息
                        //主要用于更新车辆到达时间
                        string str = m.GetLaneIDStr();
                        string section = m.GetSectionID();
                        float[] ts = m.GetTsArray();
                        float[] te = m.GetTeArray();
                        for (int i = 0; i < this.LaneQueue[int.Parse(str[5].ToString())].Count(); ++i)
                        {
                            if (this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i).getID() == m.GetSender())
                            {
                                this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i).setTs(m.GetTsArray());
                                this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i).setTe(m.GetTeArray());
                                SuperVehicleManager stmp = this.LaneQueue[int.Parse(str[5].ToString())].ElementAt(i);

                                for (int j = 0; j < section.Length; j++)
                                {
                                    if (stmp.VehicleManagers[int.Parse(section[j].ToString())] != null)
                                    {
                                        stmp.VehicleManagers[int.Parse(section[j].ToString())].setTs(ts[j]);
                                        stmp.VehicleManagers[int.Parse(section[j].ToString())].setTe(te[j]);
                                    }
                                }
                            }
                        }

                        for (int j = 0; j < section.Length; j++)
                        {
                            foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[int.Parse(section[j].ToString())])
                            {
                                if (kvp.Key == m.GetSender())
                                {
                                    kvp.Value.setTs(ts[j + 1]);
                                    kvp.Value.setTe(te[j + 1]);
                                }
                            }
                        }
                        this.sortCSQueue();
                        break;
                    case Definitions.MsgRelease:                //离开临界区消息
                        /*释放对应的SCS*/
                        //将对应的临界区的消息去除
                        //string Lanestr = m.GetLaneIDStr();

                        str = m.GetSender();

                        Vehicle VehicleTemp = FindVehicleByID(str);
                         string Lanestr = VehicleTemp.Get_Previous_LaneID();
                        //CS信息，若释放，则删除对应的临界区
                        foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[int.Parse(m.GetSectionID().ToString())])
                        {
                            if (kvp.Key == m.GetSender())
                            {
                                this.CS[int.Parse(m.GetSectionID().ToString())].Remove(kvp);
                                break;
                            }
                        }
                        //LaneQueue信息，若释放，则将对应的临界区的token信息，left信息更新，其中HaveTokenCount因为其已被申请过，所以不作修改
                        for (int i = 0; i < this.LaneQueue[int.Parse(Lanestr[5].ToString())].Count(); ++i)
                        {
                            if (this.LaneQueue[int.Parse(Lanestr[5].ToString())].ElementAt(i).getID() == m.GetSender())
                            {
                                this.LaneQueue[int.Parse(Lanestr[5].ToString())].ElementAt(i).Token[int.Parse(m.GetSectionID().ToString())] = false;
                                this.LaneQueue[int.Parse(Lanestr[5].ToString())].ElementAt(i).Left[int.Parse(m.GetSectionID().ToString())] = true;
                            }
                        }

                        //将被占用临界区标志位为未被占用
                        this.Token[int.Parse(m.GetSectionID().ToString())]--;
                        //this.Authorize_CS_to_Vehicle.Remove(int.Parse(m.getSectionID().ToString())); //当前已授权车辆的信息

                        for (int i = 0; i < Authorize_CS_to_Vehicle.Count; i++)
                        {
                            List<string> ltmp = Authorize_CS_to_Vehicle[int.Parse(m.GetSectionID().ToString())];
                            foreach (string stmp in ltmp)
                            {
                                if (str == stmp)
                                {
                                    this.Authorize_CS_to_Vehicle[int.Parse(m.GetSectionID().ToString())].Remove(stmp);
                                    IsAuth[int.Parse(m.GetSectionID().ToString())] = false;
                                    break;
                                }
                            }
                            if (this.Authorize_CS_to_Vehicle[int.Parse(m.GetSectionID().ToString())].Count == 0)
                            {
                                this.Authorize_CS_to_Vehicle.Remove(int.Parse(m.GetSectionID().ToString()));
                                break;
                            }

                        }
                        this.OutPutAuthMsg(2, m);
                        break;
                    case Definitions.MsgPassing:
                        //标志车辆正在经过某临界区，无需处理
                        break;
                    case Definitions.MsgPassed:
                        //车辆离开十字路口
                        this.removePassedVehicle(m.GetSender());
                        break;
                    default:
                        System.Windows.Forms.MessageBox.Show("Error FIFO_MQ 233");
                        //System.Windows.Forms.MessageBox.Show("Unknown Message Type ------ " + m.getType(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                }
            }

            //将数据写会MainData中
            Intersection.SetVtoA_Buffer(VtoA_BufferTemp);
            MainData.UpdateIntersectionList(Intersection);
        }

        /************************************************************************/
        /* 更新个临界区的消息队列                                                                     */
        /************************************************************************/
        private void updateCSQueue(SuperVehicleManager svm)
        {
            //将SuperVehicleManger分析成多个VehicleManger
            //将VehicleManger放入CS中
            for (int i = 1; i < 5; i++)
            {
                if (svm.VehicleManagers[i] != null)
                {
                    VehicleManager vm = svm.VehicleManagers[i];           //VehicleManagers[i]用于存储不同临界区的预约消息
                    VehicleManager vm2 = new VehicleManager(vm.getID(), vm.getLaneID(), vm.getTs(), vm.getTe(),
                    vm.getCurrent_Dis(), vm.getSectionIDs(), vm.getOriginalPriority(), true);
                    vm2.setCSCount(svm.VehicleManagers[i].getCSCount());

                    //更新临界区的消息队列
                    KeyValuePair<string, VehicleManager> kvp = new KeyValuePair<string, VehicleManager>(vm2.getID(), vm2);
                    this.CS[int.Parse(vm2.getSectionIDs())].Add(kvp);
                }
            }
        }

        /************************************************************************/
        /* 将各临界区的申请车辆按照到达时间的先后顺序进行排序                                                                     */
        /************************************************************************/
        private void sortCSQueue()
        {
            for (int i = 1; i < 5; i++)
            {
                if (this.CS[i].Count != 0)
                {
                    for (int j = 0; j < this.CS[i].Count; j++)
                    {
                        for (int k = j + 1; k < this.CS[i].Count; k++)
                        {
                            if (this.CS[i].ElementAt(j).Value.getTs() > this.CS[i].ElementAt(k).Value.getTs())
                            {
                                KeyValuePair<string, VehicleManager> kvp;  //前面车辆的到达时间大于后面车辆的到达时间，两调换顺序
                                kvp = this.CS[i].ElementAt(j);
                                this.CS[i][j] = this.CS[i].ElementAt(k);
                                this.CS[i][k] = kvp;
                            }
                        }
                    }
                }
            }
        }

        /************************************************************************/
        /* 将过了临界区的车辆删除，并释放占用的资源,
         * ID为车辆的编号                                                                     */
        /************************************************************************/
        private void removePassedVehicle(string ID)
        {
            Vehicle VehicleTemp = FindVehicleByID(ID);
            string LaneIDPrevious = VehicleTemp.Get_Previous_LaneID(); //车辆之前所在的车道序号

            int LaneID = int.Parse(LaneIDPrevious[5].ToString());
            if (this.LaneQueue[LaneID].Count == 0)
            {
                return;
            }
            //删除车道车辆列表中的车辆
            foreach (SuperVehicleManager stmp in LaneQueue[LaneID])
            {
                if (stmp.ID == ID)
                {
                    this.LaneQueue[LaneID].Remove(stmp);
                    break;
                }
            }
            //将申请过临界区的车辆释放
            for (int i = 1; i < 5; i++)
            {
                foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[i])
                {
                    if (kvp.Key == ID)
                    {
                        this.CS[i].Remove(kvp);
                        break;
                    }
                }
            }
            //将授权过的的车辆释放
            for (int i = 0; i < Authorized_Vehicle_Sequence.Count; ++i)
            {
                if (this.Authorized_Vehicle_Sequence.ElementAt(i) == ID)
                {
                    this.Authorized_Vehicle_Sequence.RemoveAt(i);
                }
            }
            //将授权过的临界区的释放
            for (int i = 1; i < 5; i++)
            {
                if (this.Authorize_CS_to_Vehicle.ContainsKey(i) == true)
                {
                    foreach (string stmp in Authorize_CS_to_Vehicle[i])
                    {
                        if (stmp == ID)
                        {
                            this.Authorize_CS_to_Vehicle[i].Remove(stmp);
                            break;
                        }
                    }
                }
            }
            return;
        }


        /************************************************************************/
        /* 对车辆进行授权                                                                         */
        /************************************************************************/
        private void processLeftVehicles(Intersection Intersection)
        {
            
                string s = null;
                int CSID = 0;
                string ID = null;

                //被授权车辆超过 Definitions.MaxAuthNum 辆
                if (this.Authorized_Vehicle_Sequence.Count > this.MaxAuthNum)
                {
                    System.Windows.Forms.MessageBox.Show("the num of authorized vehicle is more than  Definitions.MaxAuthNum");
                    return;
                }

                s = null;
                if (!IsCSEmpty())           //判断各临界区的申请队列是否为空 ,
                {
                    //若存在临界区未被占用
                    SuperVehicleManager svmp = null;
                    while ((svmp = this.GetArriveFirstSCSCar(Intersection)) != null)
                    {
                        //临界区未分配完毕，则继续
                        if (this.Token[1] == 0 && this.Token[2] == 0 && this.Token[3] == 0 && this.Token[4] == 0)
                        {
                            // continue;
                        }
                        else
                        {
                            break;
                        }

                        //被选中车辆的ID
                        ID = svmp.getID();

                        //找到车辆Vehicle对象的LaneID                        
                        string LaneID = FindVehicleByID(ID).Get_Current_LaneID();                        

                        //被选中车辆的CSID 
                        CSID = int.Parse(svmp.SectionID.ElementAt(0).ToString());

                        for (int k = 1; k <= this.MaxAuthNum / 4; k++)   //K表示第几辆车，必须小于最大授权车辆数目
                        {
                            if (k == 1)
                            {
                                if (ID != null
                                           && (this.isTokenSequenceIllegal(int.Parse(LaneID[5].ToString()), ID, CSID, ref s) == false)
                                           && (this.isFirstVehicleInLane(int.Parse(LaneID[5].ToString()), ID, CSID) == true))
                                {
                                    for (int i = 1; i <= svmp.CS_Count; i++)
                                    {
                                        CSID = int.Parse(svmp.SectionID.ElementAt(i - 1).ToString());
                                                                                

                                        //********************
                                        //xc 2018.6.4这里不会断点，一直没有执行到
                                        //可能和BUG有关
                                        //*****************
                                        if (this.Authorize_CS_to_Vehicle.Keys.Contains(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())))      //将车辆的CSID和ID添加到 Authorize_CS_to_Vehicle
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                            //如果Authorize_CS_to_Vehicle已经有 该车辆所需的CSID，则需要检查该车辆和 其他需要此CSID 的车辆是不是同一个车道上的车辆,如果不是，则删除

                                            Vehicle VehicleTemp1 = FindVehicleByID(ID);
                                            string LaneIDPrevious1 = VehicleTemp1.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp1 = int.Parse(LaneIDPrevious1[5].ToString());

                                            int temp = int.Parse(svmp.SectionID.ElementAt(i - 1).ToString());
                                            Vehicle VehicleTemp2 = FindVehicleByID(Authorize_CS_to_Vehicle[temp].ElementAt(0));
                                            string LaneIDPrevious2 = VehicleTemp2.Get_Current_LaneID(); //车辆之前所在的车道序号
                                            int LaneIDtemp2 = int.Parse(LaneIDPrevious2[5].ToString());


                                            if (LaneIDtemp1 != LaneIDtemp2)
                                            //if (ID.ElementAt(0) != Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].ElementAt(0).ElementAt(0))
                                            {
                                                this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                            }
                                        }
                                        else
                                        {
                                            //
                                            this.Authorize_CS_to_Vehicle.Add(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), null);
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())] = new List<string>();     //可以值是null，用的时候在实例化。
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                        }


                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)   //不会死锁
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()), ID);
                                        }
                                        else    //会产生死锁   第一辆车不授权，后面的车辆更不授权。
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Remove(ID);
                                            //如果SCID所对应的 list的数量为0，说明 此临界区对应的队列 为空。没有车辆了 
                                            if (this.Authorize_CS_to_Vehicle[int.Parse(svmp.SectionID.ElementAt(i - 1).ToString())].Count == 0)
                                            {
                                                this.Authorize_CS_to_Vehicle.Remove(int.Parse(svmp.SectionID.ElementAt(i - 1).ToString()));
                                                break;
                                            }
                                            break;
                                        }

                                    }
                                    // this.Already_Authorized_All_CS_Vehicles.Add(ID);
                                    this.AddCarInAuthList(svmp);

                                }

                            }
                            else            // k!=1 , 第一辆车 后面的车辆
                            {

                                string ID0 = ID;
                                //被选中车辆的ID
                                Vehicle vetemp = CarInLaneNext(ID0);
                                ID = vetemp.Get_ID();
                                LaneID = FindVehicleByID(ID).Get_Current_LaneID();

                                if (ID != ID0)
                                {
                                    //continue;
                                }
                                else
                                {
                                    break;
                                }

                                SuperVehicleManager svmplater = null;
                                for (int i = 1; i <= 4; i++)
                                {
                                    foreach (SuperVehicleManager svmpl in LaneQueue[i])
                                    {
                                        if (ID == svmpl.getID())
                                        {
                                            svmplater = svmpl;
                                        }
                                    }
                                }

                                CSID = int.Parse(svmplater.SectionID.ElementAt(0).ToString());

                                if (ID != null
                                        && (this.isTokenSequenceIllegal(int.Parse(LaneID[5].ToString()), ID, CSID, ref s) == false))
                                // && (this.isFirstVehicleInLane(int.Parse(ID[0].ToString()), ID, CSID) == true))
                                {

                                    for (int i = 1; i <= svmplater.CS_Count; i++)
                                    {
                                        CSID = int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString());

                                        if (this.Authorize_CS_to_Vehicle.Keys.Contains(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())))      //将车辆的CSID和ID添加到 Authorize_CS_to_Vehicle
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                        }
                                        else
                                        {
                                            //
                                            this.Authorize_CS_to_Vehicle.Add(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()), null);
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())] = new List<string>();     //可以值是null，用的时候在实例化。
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Add(ID);
                                        }

                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)   //不会死锁
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmplater.Original_Priority, int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()), Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()), ID);
                                        }
                                        else    //会产生死锁   第一辆车不授权，后面的车辆更不授权。
                                        {
                                            this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Remove(ID);

                                            if (this.Authorize_CS_to_Vehicle[int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString())].Count == 0)
                                            {
                                                this.Authorize_CS_to_Vehicle.Remove(int.Parse(svmplater.SectionID.ElementAt(i - 1).ToString()));
                                                break;
                                            }
                                            break;
                                        }

                                    }

                                    // this.Already_Authorized_All_CS_Vehicles.Add(ID);

                                }
                                this.AddCarInAuthList(svmplater);

                            }

                        }


                            /************************************************************************/
                            /* 第二次多车授权                                                       */
                            /************************************************************************/
                            //多车授权的车辆已经占用4个临界区 没有临界区剩余，不用授权了
                            if (Authorize_CS_to_Vehicle.Count == 4)
                            {
                                break;
                            }


                            //多车已经占用了3个临界区，还剩一个临界区
                            else if (Authorize_CS_to_Vehicle.Count == 3)
                            {
                                SuperVehicleManager svmpauththree = null;
                                svmpauththree = GetOneEmptyCSCar();
                                if (svmpauththree == null)
                                {
                                    break;
                                }

                                for (int d = 1; d <= this.MaxAuthNum / 4; d++)
                                {
                                    CSID = int.Parse(svmpauththree.SectionID.ElementAt(0).ToString());
                                    ID = svmpauththree.getID();
                                    if (svmpauththree.CS_Count != 1)
                                    {
                                        break;
                                    }
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);
                                        }
                                        break;
                                    }
                                    this.AddCarInAuthList(svmpauththree);

                                    //拿到车辆所在道路LaneID
                                    Vehicle vtemp = CarInLaneNext(ID);
                                    string IDLter = vtemp.Get_ID();
                                    LaneID = vtemp.Get_Current_LaneID();

                                    if (IDLter == ID)
                                    {
                                        break;
                                    }
                                    if (IDLter != null)
                                    {
                                        foreach (SuperVehicleManager sv in LaneQueue[int.Parse(LaneID[5].ToString())])
                                        {
                                            if (IDLter == sv.getID())
                                            {
                                                svmpauththree = sv;
                                            }
                                        }
                                    }

                                }

                            }


                            //多车占有2个临界区，还剩余2个临界区
                            else if (Authorize_CS_to_Vehicle.Count == 2)
                            {
                                bool FLag = true;
                                SuperVehicleManager svmpauthtwo = null;
                                svmpauthtwo = GetTwoEmptyCSCar();
                                if (svmpauthtwo == null)
                                {
                                    break;
                                }
                                int[] EmptyCs = new int[3];     //记录空闲的临界区的csid 是几
                                for (int q = 0; q < 3; q++)     //初始化
                                {
                                    EmptyCs[q] = 0;
                                }
                                int n = 1, j = 1;
                                for (n = 1, j = 1; n <= 4; n++)
                                {
                                    if (IsAuth[n] == false)
                                    {
                                        EmptyCs[j] = n;
                                        j++;
                                    }
                                }
                                int Sum = 0;
                                for (int m = 1; m < j; m++)
                                {
                                    Sum += EmptyCs[m];
                                }



                                for (int d = 1; d <= this.MaxAuthNum / 4; d++)
                                {
                                    if (svmpauthtwo.CS_Count > 2)
                                    {
                                        break;
                                    }

                                    if (svmpauthtwo.CS_Count == 1)
                                    {
                                        CSID = int.Parse(svmpauthtwo.SectionID.ElementAt(0).ToString());
                                        ID = svmpauthtwo.getID();
                                        if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                        {
                                            Authorize_CS_to_Vehicle.Add(CSID, null);
                                            Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }
                                        else
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }
                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(CSID, ID);
                                        }
                                        else
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);
                                            }
                                        }
                                        this.AddCarInAuthList(svmpauthtwo);
                                    }
                                    else
                                    {

                                        for (int q = 1; q <= 2; q++)
                                        {
                                            CSID = int.Parse(svmpauthtwo.SectionID.ElementAt(q - 1).ToString());
                                            ID = svmpauthtwo.getID();
                                            if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                            {
                                                Authorize_CS_to_Vehicle.Add(CSID, null);
                                                Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                                Authorize_CS_to_Vehicle[CSID].Add(ID);
                                            }
                                            else
                                            {
                                                Authorize_CS_to_Vehicle[CSID].Add(ID);
                                            }
                                            if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                            {
                                                this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                                IsAuth[CSID] = true;
                                                this.setToken(CSID, ID);
                                                this.AddCarInAuthList(svmpauthtwo);
                                            }
                                            else
                                            {
                                                Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                                if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                                {
                                                    Authorize_CS_to_Vehicle.Remove(CSID);
                                                }
                                            }
                                        }


                                    }

                                    Vehicle vtemp = CarInLaneNext(ID);
                                    string IDLter = vtemp.Get_ID();
                                    LaneID = vtemp.Get_Current_LaneID();
                                    //string IDLter = CarInLaneNext(ID);
                                    if (IDLter == ID)
                                    {
                                        break;
                                    }
                                    if (IDLter != null)
                                    {
                                        foreach (SuperVehicleManager sv in LaneQueue[int.Parse(LaneID[5].ToString())])
                                        {
                                            if (IDLter == sv.getID())
                                            {
                                                svmpauthtwo = sv;
                                                break;
                                            }
                                        }
                                    }
                                    //需要判断第二辆以后的车是否包含主干道所需的两个临界区 例如主干道需要21/2，后来找到的车辆需要4/42，则2为重复的
                                    if (svmpauthtwo.CS_Count == 2)
                                    {
                                        FLag = GetTwoEmptyCSOtherLaneCarIsConTwoTrueCS(svmpauthtwo, Sum);
                                        if (FLag == true)
                                        {
                                            break;
                                        }
                                    }

                                }

                            }

                            //多车占有2个临界区，还剩余2个临界区
                            else if (Authorize_CS_to_Vehicle.Count == 1)
                            {
                                bool FLag = true;
                                SuperVehicleManager svmpauthone = null;
                                svmpauthone = GetThreeEmptyCSCar();
                                if (svmpauthone == null)
                                {
                                    break;
                                }
                                int[] EmptyCs = new int[4];     //记录空闲的临界区的csid 是几
                                for (int q = 0; q < 4; q++)     //初始化
                                {
                                    EmptyCs[q] = 0;
                                }
                                int n = 1, j = 1;
                                for (n = 1, j = 1; n <= 4; n++)
                                {
                                    if (IsAuth[n] == false)
                                    {
                                        EmptyCs[j] = n;
                                        j++;
                                    }
                                }
                                int Sum = 0;
                                for (int m = 1; m < j; m++)
                                {
                                    Sum += EmptyCs[m];
                                }

                                for (int d = 1; d <= this.MaxAuthNum / 4; d++)
                                {
                                    if (svmpauthone.CS_Count > 3)
                                    {
                                        break;
                                    }
                                    if (svmpauthone.CS_Count == 1)
                                    {
                                        CSID = int.Parse(svmpauthone.SectionID.ElementAt(0).ToString());
                                        ID = svmpauthone.getID();
                                        if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                        {
                                            Authorize_CS_to_Vehicle.Add(CSID, null);
                                            Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }
                                        else
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Add(ID);
                                        }
                                        if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                        {
                                            this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                            IsAuth[CSID] = true;
                                            this.setToken(CSID, ID);
                                            this.AddCarInAuthList(svmpauthone);
                                        }
                                        else
                                        {
                                            Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                            if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                            {
                                                Authorize_CS_to_Vehicle.Remove(CSID);
                                            }
                                        }

                                    }
                                    else
                                    {

                                        for (int q = 1; q <= svmpauthone.CS_Count; q++)
                                        {
                                            CSID = int.Parse(svmpauthone.SectionID.ElementAt(q - 1).ToString());
                                            ID = svmpauthone.getID();
                                            if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                            {
                                                Authorize_CS_to_Vehicle.Add(CSID, null);
                                                Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                                Authorize_CS_to_Vehicle[CSID].Add(ID);
                                            }
                                            else
                                            {
                                                Authorize_CS_to_Vehicle[CSID].Add(ID);
                                            }
                                            if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                            {
                                                this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                                IsAuth[CSID] = true;
                                                this.setToken(CSID, ID);
                                                this.AddCarInAuthList(svmpauthone);
                                            }
                                            else
                                            {
                                                Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                                if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                                {
                                                    Authorize_CS_to_Vehicle.Remove(CSID);
                                                }
                                            }
                                        }


                                    }


                                    Vehicle vtemp = CarInLaneNext(ID);
                                    string IDLter = vtemp.Get_ID();
                                    LaneID = vtemp.Get_Current_LaneID();
                                    //string IDLter = CarInLaneNext(ID);
                                    if (IDLter == ID)
                                    {
                                        break;
                                    }
                                    if (IDLter != null)
                                    {
                                        foreach (SuperVehicleManager sv in LaneQueue[int.Parse(LaneID[5].ToString())])
                                        {
                                            if (IDLter == sv.getID())
                                            {
                                                svmpauthone = sv;
                                                break;
                                            }
                                        }
                                    }
                                    //需要判断第二辆以后的车是否包含主干道所需的一个临界区 看相应函数注释即可
                                    if (svmpauthone.CS_Count == 3)
                                    {
                                        FLag = GetThreeEmptyCSOtherLaneCarIsDengyuThreeTrueCS(svmpauthone, Sum);
                                        if (FLag == true)
                                        {
                                            break;
                                        }
                                    }
                                    else if (svmpauthone.CS_Count == 2)
                                    {
                                        FLag = GetThreeEmptyCSOtherLaneCarIsConOneTrueCS(svmpauthone, Sum);
                                        if (FLag == true)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }

                      


                        
                            //第三次多车授权
                            if (Authorize_CS_to_Vehicle.Count == 4)   //多车授权的车辆已经占用4个临界区
                            {
                                break;
                            }
                            else if (Authorize_CS_to_Vehicle.Count == 3)
                            {
                                SuperVehicleManager svmpauththree = null;
                                svmpauththree = GetOneEmptyCSCar();
                                if (svmpauththree == null)
                                {
                                    break;
                                }

                                for (int d = 1; d <= this.MaxAuthNum / 4; d++)
                                {
                                    CSID = int.Parse(svmpauththree.SectionID.ElementAt(0).ToString());
                                    ID = svmpauththree.getID();
                                    if (svmpauththree.CS_Count != 1)
                                    {
                                        break;
                                    }
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                        this.AddCarInAuthList(svmpauththree);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);
                                        }
                                        break;
                                    }


                                    Vehicle vtemp = CarInLaneNext(ID);
                                    string IDLter = vtemp.Get_ID();
                                    LaneID = vtemp.Get_Current_LaneID();
                                    //string IDLter = CarInLaneNext(ID);
                                    if (IDLter == ID)
                                    {
                                        break;
                                    }
                                    if (IDLter != null)
                                    {
                                        foreach (SuperVehicleManager sv in LaneQueue[int.Parse(LaneID[5].ToString())])
                                        {
                                            if (IDLter == sv.getID())
                                            {
                                                svmpauththree = sv;
                                            }
                                        }
                                    }

                                }
                            }
                            else if (Authorize_CS_to_Vehicle.Count == 2)
                            {
                                //bool FLag = true;
                                SuperVehicleManager svmpauthtwo = null;
                                svmpauthtwo = GetTwoEmptyCSCar();
                                if (svmpauthtwo == null)
                                {
                                    break;
                                }


                                for (int d = 1; d <= this.MaxAuthNum / 4; d++)
                                {
                                    CSID = int.Parse(svmpauthtwo.SectionID.ElementAt(0).ToString());
                                    ID = svmpauthtwo.getID();
                                    if (svmpauthtwo.CS_Count != 1)
                                    {
                                        break;
                                    }
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                        this.AddCarInAuthList(svmpauthtwo);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);
                                        }
                                        break;
                                    }

                                    Vehicle NextVehicleTemp = CarInLaneNext(ID);
                                    string IDLter = NextVehicleTemp.Get_ID();
                                    LaneID = NextVehicleTemp.Get_Current_LaneID();

                                    if (IDLter == ID)
                                    {
                                        break;
                                    }
                                    if (IDLter != null)
                                    {
                                        foreach (SuperVehicleManager sv in LaneQueue[int.Parse(LaneID[5].ToString())])
                                        {
                                            if (IDLter == sv.getID())
                                            {
                                                svmpauthtwo = sv;
                                            }
                                        }
                                    }

                                }
                            }
                       



                            //第四次多车授权
                            if (Authorize_CS_to_Vehicle.Count == 4)   //多车授权的车辆已经占用4个临界区
                            {
                                break;
                            }
                            else if (Authorize_CS_to_Vehicle.Count == 3)
                            {
                                SuperVehicleManager svmpauththree = null;
                                svmpauththree = GetOneEmptyCSCar();
                                if (svmpauththree == null)
                                {
                                    break;
                                }

                                for (int d = 1; d <= this.MaxAuthNum / 4; d++)
                                {
                                    CSID = int.Parse(svmpauththree.SectionID.ElementAt(0).ToString());
                                    ID = svmpauththree.getID();
                                    if (svmpauththree.CS_Count != 1)
                                    {
                                        break;
                                    }
                                    if (!Authorize_CS_to_Vehicle.ContainsKey(CSID))
                                    {
                                        Authorize_CS_to_Vehicle.Add(CSID, null);
                                        Authorize_CS_to_Vehicle[CSID] = new List<string>();
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Add(ID);
                                    }
                                    if (this.isTokenSequenceDeadLock(this.Authorize_CS_to_Vehicle) != true)
                                    {
                                        this.sendMessage(Definitions.MsgAuthorize, ID, svmp.Original_Priority, CSID, Intersection);
                                        IsAuth[CSID] = true;
                                        this.setToken(CSID, ID);
                                    }
                                    else
                                    {
                                        Authorize_CS_to_Vehicle[CSID].Remove(ID);
                                        if (Authorize_CS_to_Vehicle[CSID].Count == 0)
                                        {
                                            Authorize_CS_to_Vehicle.Remove(CSID);
                                        }
                                        break;
                                    }
                                    this.AddCarInAuthList(svmpauththree);

                                    Vehicle vtemp = CarInLaneNext(ID);
                                    string IDLter = vtemp.Get_ID();
                                    LaneID = vtemp.Get_Current_LaneID();
                                    //string IDLter = CarInLaneNext(ID);
                                    if (IDLter == ID)
                                    {
                                        break;
                                    }
                                    if (IDLter != null)
                                    {
                                        foreach (SuperVehicleManager sv in LaneQueue[int.Parse(LaneID[5].ToString())])
                                        {
                                            if (IDLter == sv.getID())
                                            {
                                                svmpauththree = sv;
                                            }
                                        }
                                    }

                                }
                            }                      


                    }
                }

        }

        /************************************************************************/
        /* 找到当只有一个空闲临界区的时候，只需占用此空闲临界区的车辆
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetOneEmptyCSCar()
        {
            SuperVehicleManager svmp = null;
            int EmptyCs = 0;     //记录空闲的临界区的csid 是几
            if (Authorize_CS_to_Vehicle.Count != 3)
            {
                return null;
            }

            for (int n = 1; n <= 4; n++)
            {
                if (IsAuth[n] == false)
                {
                    EmptyCs = n;
                    if (CS[n].Count != 0)
                    {
                        break;
                    }

                }
            }
            switch (EmptyCs)
            {
                case 0:
                    return null;
                case 1:
                    if (LaneQueue[3].Count >= 1)
                    {
                        svmp = LaneQueue[3].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 2:
                    if (LaneQueue[2].Count >= 1)
                    {
                        svmp = LaneQueue[2].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 3:
                    if (LaneQueue[1].Count >= 1)
                    {
                        svmp = LaneQueue[1].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 4:
                    if (LaneQueue[4].Count >= 1)
                    {
                        svmp = LaneQueue[4].ElementAt(0);
                        if (svmp.CS_Count != 1)
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                default:
                    System.Windows.Forms.MessageBox.Show("EmptyCs error!");
                    break;
            }
            return svmp;
        }

        /************************************************************************/
        /* 找到当只有两个空闲临界区的时候，只需占用此空闲临界区的车辆
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetTwoEmptyCSCar()
        {
            SuperVehicleManager svmp = null;
            SuperVehicleManager[] svmpshuzu = new SuperVehicleManager[3];  //用来存放符合条件的两辆车
            int[] EmptyCs = new int[3];     //记录空闲的临界区的csid 
            for (int q = 0; q < 3; q++)     //初始化
            {
                EmptyCs[q] = 0;
            }

            //判断是否剩余两个临界区
            if (Authorize_CS_to_Vehicle.Count != 2)
            {
                return null;
            }


            //知道没有使用的
            int n = 1;
            int j = 1;
            for (n = 1; n <= 4; n++)
            {
                if (IsAuth[n] == false) //没有被使用
                {
                    EmptyCs[j] = n;
                    j++;
                }
            }

            //没使用的CCSID之和，根据和判断剩余临界区的情况
            int Sum = 0;
            for (int m = 1; m < j; m++)
            {
                Sum += EmptyCs[m];
            }

            int i = 1;
            switch (Sum)    //临界区ccsid之和
            {

                //剩余的是1号、4号临界区      2号、3号临界区
                case 5:
                    if (EmptyCs[1] == 1 && EmptyCs[2] == 4)
                    {
                        if ((LaneQueue[3].Count >= 1) || (LaneQueue[4].Count >= 1))
                        {

                            if (LaneQueue[3].Count != 0)
                            {
                                if (LaneQueue[3].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                    i++;
                                }
                            }
                            if (LaneQueue[4].Count != 0)
                            {
                                if (LaneQueue[4].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                    i++;
                                }
                            }
                        }
                        else
                        {
                            return null;
                        }
                        break;
                    }
                    else
                    {
                        
                        if ((LaneQueue[1].Count >= 1) || (LaneQueue[2].Count >= 1))
                        {

                            if (LaneQueue[1].Count != 0)
                            {
                                if (LaneQueue[1].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                    i++;
                                }
                            }
                            if (LaneQueue[2].Count != 0)
                            {
                                if (LaneQueue[2].ElementAt(0).CS_Count <= 1)
                                {
                                    svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                    i++;
                                }
                            }
                        }
                        else
                        {
                            return null;
                        }
                        break;
                    }

                //剩余1号、2号临界区
                case 3:
                    if ((LaneQueue[2].Count >= 1) || (LaneQueue[3].Count >= 1))   //判断是否有申请临界区的车辆SuperVehicleManager
                    {
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }
                        else if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }                  
                        else
                        {
                            return null;
                        }
                        //if ((LaneQueue[2].ElementAt(0).CS_Count <= 2) || (LaneQueue[3].ElementAt(0).CS_Count == 1))
                        //{
                            
                        //    if (LaneQueue[2].Count != 0)
                        //    {
                        //        if (LaneQueue[2].ElementAt(0).CS_Count <= 2)
                        //        {
                        //            svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                        //            i++;
                        //        }
                        //    }
                        //    if (LaneQueue[3].Count != 0)
                        //    {
                        //        if (LaneQueue[3].ElementAt(0).CS_Count <= 1)
                        //        {
                        //            svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                        //            i++;
                        //        }
                        //    }

                        //}
                        //else
                        //{
                        //    return null;
                        //}
                    }
                    else
                    {
                        return null;
                    }
                    break;

                    //剩余1号、3号临界区
                case 4:
                    if ((LaneQueue[3].Count >= 1) || (LaneQueue[1].Count >= 1))
                    {                        
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }                          
                       
                    }
                    else
                    {
                        return null;
                    }
                    break;

                    //剩余3号、4号临界区
                case 7:
                    if ((LaneQueue[1].Count >= 1) || (LaneQueue[4].Count >= 1))
                    {                        
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }                           
     
                    }
                    else
                    {
                        return null;
                    }
                    break;

                    //剩余2号、4号临界区
                case 6:
                    if ((LaneQueue[4].Count >= 1) || (LaneQueue[2].Count >= 1))
                    {                       
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 1)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }                           
                       
                    }
                    else
                    {
                        return null;
                    }
                    break;
                default:
                    return null;                  
            }


            if (i == 3)          //说明找到2辆车
            {
                if (svmpshuzu[1].Ts[1] < svmpshuzu[2].Ts[1])
                {
                    svmp = svmpshuzu[1];
                }
                else
                {
                    svmp = svmpshuzu[2];
                }
            }
            else if (i == 2)     //说明找到1辆车
            {
                svmp = svmpshuzu[1];
            }
            else if (i == 1)     //说明找到0辆车
            {
                return null;
            }

            return svmp;
        }

        /************************************************************************/
        /* 当只有两个空闲临界区的时候
         *   判断其他车道找到的车辆是否包括了 主干道车辆所需的两个临界区 
         *   false 为不占用  true为占用                                        */
        /************************************************************************/
        private bool GetTwoEmptyCSOtherLaneCarIsConTwoTrueCS(SuperVehicleManager svm, int m)
        {
            string VehicleID = svm.getID();
            Vehicle VehicleTemp = FindVehicleByID(VehicleID);
            string LaneID = VehicleTemp.Get_Current_LaneID();

            switch (m)
            {
                case 3:
                    if (int.Parse(LaneID.ElementAt(5).ToString()) == 2)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                    
                case 4:
                    if (int.Parse(LaneID.ElementAt(5).ToString()) == 3)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                    
                case 7:
                    if (int.Parse(LaneID.ElementAt(5).ToString()) == 1)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                   
                case 6:
                    if (int.Parse(LaneID.ElementAt(5).ToString()) == 4)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                    
                default:
                    // MessageBox.Show("error1234654");
                    break;
            }
            return true;
        }


        /************************************************************************/
        /* 找到当只有三个空闲临界区的时候，只需占用此空闲临界区的车辆           */
        /************************************************************************/
        private SuperVehicleManager GetThreeEmptyCSCar()
        {
            SuperVehicleManager svmp = null;
            SuperVehicleManager[] svmpshuzu = new SuperVehicleManager[4];  //用来存放符合条件的两辆车
            int[] EmptyCs = new int[4];     //记录空闲的临界区的csid 是几
            for (int q = 0; q < 4; q++)     //初始化
            {
                EmptyCs[q] = 0;
            }
            if (Authorize_CS_to_Vehicle.Count != 1)
            {
                return null;
            }
            int n = 1;
            int j = 1;
            for (n = 1; n <= 4; n++)
            {
                if (IsAuth[n] == false)
                {

                    EmptyCs[j] = n;
                    j++;
                }
            }

            int Sum = 0;
            for (int m = 1; m < j; m++)
            {
                Sum += EmptyCs[m];
            }

            int i = 1;
            switch (Sum)
            {
                case 0:
                    return null;                    

                case 9:
                    if ((LaneQueue[1].Count >= 1) || (LaneQueue[4].Count >= 1) || (LaneQueue[2].Count >= 1))
                    {
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }

                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 8:
                    if ((LaneQueue[3].Count >= 1) || (LaneQueue[1].Count >= 1) || (LaneQueue[4].Count >= 1))
                    {
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }

                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 7:
                    if ((LaneQueue[4].Count >= 1) || (LaneQueue[2].Count >= 1) || (LaneQueue[3].Count >= 1))
                    {

                        if (LaneQueue[4].Count != 0)
                        {
                            if (LaneQueue[4].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[4].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }

                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 6:
                    if ((LaneQueue[2].Count >= 1) || (LaneQueue[3].Count >= 1) || (LaneQueue[1].Count >= 1))
                    {
                        if (LaneQueue[2].Count != 0)
                        {
                            if (LaneQueue[2].ElementAt(0).CS_Count <= 3)
                            {
                                svmpshuzu[i] = LaneQueue[2].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[3].Count != 0)
                        {
                            if (LaneQueue[3].ElementAt(0).CS_Count <= 2)
                            {
                                svmpshuzu[i] = LaneQueue[3].ElementAt(0);
                                i++;
                            }
                        }
                        if (LaneQueue[1].Count != 0)
                        {
                            if (LaneQueue[1].ElementAt(0).CS_Count == 1)
                            {
                                svmpshuzu[i] = LaneQueue[1].ElementAt(0);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        return null;
                    }
                    break;
                default:
                    return null;                   

            }


            if (i == 4)                   //说明找到3辆车
            {
                int min = 1;
                for (int w = 2; w < 4; w++)
                {
                    if (svmpshuzu[w].Ts[1] < svmpshuzu[min].Ts[1])
                    {
                        min = w;
                    }
                }
                svmp = svmpshuzu[min];
            }
            else if (i == 3)              //说明找到2辆车
            {
                if (svmpshuzu[1].Ts[1] < svmpshuzu[2].Ts[1])
                {
                    svmp = svmpshuzu[1];
                }
                else
                {
                    svmp = svmpshuzu[2];
                }
            }
            else if (i == 2)            //说明找到1辆车
            {
                svmp = svmpshuzu[1];
            }
            else if (i == 1)            //说明找到0辆车
            {
                return null;
            }

            return svmp;
        }


        /************************************************************************/
        /* 当只有三个空闲临界区的时候
         *   判断其他车道找到的车辆是否包括了 主干道车辆所需的一个临界区 
         *   false 为不占用  true为占用    
         *   此种情况检查的是 当主干道占用CSID=1，次干道为车辆ID为2XXXX，此时多车次干道多车授权时，
         *   第二辆及以后的车只能需要一个临界区，若需要两个临界区CSID=1,2，则出错。返回false。 
         *   此函数用于在判断找到的后续车辆需要的是两个临界区时，*/
        /************************************************************************/
        private bool GetThreeEmptyCSOtherLaneCarIsConOneTrueCS(SuperVehicleManager svm, int m)
        {
            switch (m)
            {
                case 9:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 2)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                    

                case 8:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 4)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                   

                case 7:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 3)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                    

                case 6:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                    

                default:
                    //MessageBox.Show("error1234654");
                    break;
            }

            return true;
        }

        /************************************************************************/
        /* 当只有三个空闲临界区的时候
         *   判断其他车道找到的车辆是否包括了 主干道车辆所需的一个临界区 
         *   false 为不占用  true为占用    
         *   此种情况检查的是 当主干道占用CSID=1，次干道上的车辆ID只能为1XXXX。 
         *   此函数用于在判断找到的后续车辆需要的是两个临界区时，*/
        /************************************************************************/
        private bool GetThreeEmptyCSOtherLaneCarIsDengyuThreeTrueCS(SuperVehicleManager svm, int m)
        {
            switch (m)
            {
                case 9:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 1)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                   

                case 8:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 3)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                    

                case 7:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 4)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                    

                case 6:
                    if (int.Parse(svm.getID().ElementAt(0).ToString()) == 2)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                    

                default:
                    //MessageBox.Show("error1234654");
                    break;
            }
            return true;
        }




        /************************************************************************/
        /* 第三次授权
         * 找到当只有两个空闲临界区的时候，只需占用此空闲临界区的车辆
         *  此时找的车辆都是只占用一个临界区的车辆                               */
        /************************************************************************/
        private SuperVehicleManager GetThirdTwoEmptyCSCar()
        {
            SuperVehicleManager[] svmp = new SuperVehicleManager[3];
            int EmptyCs = 0;     //记录空闲的临界区的csid 是几

            if (Authorize_CS_to_Vehicle.Count != 2)
            {
                return null;
            }

            for (int n = 1; n <= 4; n++)
            {
                if (IsAuth[n] == false)
                {
                    EmptyCs = n;
                    if (CS[n].Count != 0)
                    {
                        break;
                    }
                }
            }
            int i = 1;
            switch (EmptyCs)
            {
                case 0:
                    return null;
                case 1:
                    if (LaneQueue[3].Count >= 1)
                    {
                        svmp[i] = LaneQueue[3].ElementAt(0);
                        if (svmp[i].CS_Count != 1)
                        {
                            return null;
                        }
                        i++;
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 2:
                    if (LaneQueue[2].Count >= 1)
                    {
                        svmp[i] = LaneQueue[2].ElementAt(0);
                        if (svmp[i].CS_Count != 1)
                        {
                            return null;
                        }
                        i++;
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 3:
                    if (LaneQueue[1].Count >= 1)
                    {
                        svmp[i] = LaneQueue[1].ElementAt(0);
                        if (svmp[i].CS_Count != 1)
                        {
                            return null;
                        }
                        i++;
                    }
                    else
                    {
                        return null;
                    }
                    break;
                case 4:
                    if (LaneQueue[4].Count >= 1)
                    {
                        svmp[i] = LaneQueue[4].ElementAt(0);
                        if (svmp[i].CS_Count != 1)
                        {
                            return null;
                        }
                        i++;
                    }
                    else
                    {
                        return null;
                    }
                    break;
                default:
                    System.Windows.Forms.MessageBox.Show("EmptyCs error!");
                    break;
            }

            int Flag = 1;
            if (i == 3)
            {
                if (svmp[2].Ts[1] < svmp[Flag].Ts[1])
                {
                    return svmp[2];
                }
                else
                {
                    return svmp[Flag];
                }
            }
            else if (i == 2)
            {
                return svmp[Flag];
            }
            else
            {
                return null;
            }
        }





        /************************************************************************/
        /* 找到车辆到达所需第一个临界区(即为车道号)时间最短的车辆
         *                                                                       */
        /************************************************************************/
        private SuperVehicleManager GetArriveFirstSCSCar(Intersection Intersection)
        {
            SuperVehicleManager svmp = null;
            SuperVehicleManager[] svm = new SuperVehicleManager[5];

            float[] time = new float[5]; //其中每一个元素 对应其LaneQueue中 第一辆车到达 其所需第一个临界区的时间
            string[] IDString = new string[5];
            int[] IDInt = new int[5];
            int[] xiabiao = new int[5];

            for (int m = 1; m <= 4; m++)  //初始化 使其时间都为0
            {
                xiabiao[m] = 9999;
            }

            //若LaneQueue中有车辆，则将四个LaneQueue的首车添加到数组svm中
            int i = 1, j = 1;
            for (i = 1; i <= 4; i++)
            {
                if (LaneQueue[i].Count == 0)
                {
                    j++;
                    continue;
                }
                else
                {
                    svm[j] = LaneQueue[i].ElementAt(0);
                    IDString[j] = LaneQueue[i].ElementAt(0).getID();
                    j++;
                }
            }

            List<string> ListTemp = Intersection.GetReservationLst();
            //xc还没调试
            if (ListTemp.Count != 0)
            {
                for (int j1 = 1; j1 <= 4; j1++)
                {
                    for (int j2 = 0; j2 < ListTemp.Count; j2++)
                    {
                        if (svm[j1] == null)
                        {
                            continue;
                        }
                        if (svm[j1].getID() == ListTemp[j2])
                        {
                            xiabiao[j1] = j2;
                        }
                    }
                }

            }

            int Flag = 1;
            for (int m = 1; m < 4; m++)
            {
                if (xiabiao[m + 1] - xiabiao[Flag] < 0)    //if (time[m + 1] < time[m])
                {
                    Flag = m + 1;
                }
            }


            //在一个时间片内，如果选中的车辆的 第一个临界区 isSelect 被标记为 true ，则说明该车辆之前已经被选中过，此时说明没有找到 车辆
            if (svm[Flag] != null)
            {
                for (int k1 = 0; k1 < CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].Count; k1++)
                {
                    VehicleManager vmp = null;
                    vmp = CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value;
                    if (svm[Flag].getID() == vmp.getID())
                    {
                        if (CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value.isSelect == true)
                        {
                            return null;
                        }
                    }
                }
            }

            //5.10检测出已授权
            //在一个时间片内，选中的车辆的 第一个临界区 isSelect 被标记为 true
            if (Already_Authorized_All_CS_Vehicles.Contains(svm[Flag].getID()))
            {
                return null;

                //MessageBox.Show("error,该车辆的所有临界区已经被授权！");
            }

            if (svm[Flag] != null)
            {
                for (int k1 = 0; k1 < CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].Count; k1++)
                {
                    VehicleManager vmp = null;
                    vmp = CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value;
                    if (svm[Flag].getID() == vmp.getID())
                    {
                        CS[int.Parse(svm[Flag].SectionID.ElementAt(0).ToString())].ElementAt(k1).Value.isSelect = true;
                        break;
                    }
                }
            }
            return svm[Flag];
        }



        /************************************************************************/
        /* 已知一辆车的ID，判断这辆车是否在车道上  
         *  通过该车行驶的距离 与 90?? 作比较                                   */
        /************************************************************************/
        private bool IsInLane(string ID1)
        {

            for (int i = 1; i <= 4; i++)
            {
                foreach (SuperVehicleManager svmp in LaneQueue[i])
                {
                    if (ID1 == svmp.getID())
                    {
                        if (svmp.getTotal_Dis() <= 90)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        /************************************************************************/
        /* 已知一辆车的ID1，
         * 且这辆车在车道上(找的前提)，则找到这辆车所在车道上的 后续车辆的ID0   
         *                ID01 = LaneQueue[i].ElementAt(j+1).getID();           */
        /************************************************************************/
        private Vehicle CarInLaneNext(string ID00)
        {
            string ID01 = null;
            int j = -1;

            for (int i = 1; i <= 4; i++)
            {
                foreach (SuperVehicleManager svmp in LaneQueue[i])
                {
                    if (ID00 == svmp.getID())
                    {
                        j = LaneQueue[i].IndexOf(svmp);
                        if (LaneQueue[i].Count > j + 1)
                        {
                            ID01 = LaneQueue[i].ElementAt(j + 1).getID();
                        }
                        else
                        {
                            //返回ID信息不够，返回车辆Vehicle对象  xc
                            for (int k = 0; k < MainData.Map.GlobalVehicleList.Count(); k++)
                            {
                                Vehicle veh = MainData.Map.GlobalVehicleList[k];
                                if (veh.Get_ID() == ID00)
                                {
                                    return veh;
                                }
                            }
                           // return ID00;
                        }
                    }
                }

                // ID0 = LaneQueue[i].ElementAt(j+1).getID();
            }
              
            //返回ID信息不够，返回车辆Vehicle对象   xc
            for (int i = 0; i < MainData.Map.GlobalVehicleList.Count(); i++) 
            {
                Vehicle veh = MainData.Map.GlobalVehicleList[i];
                if (veh.Get_ID() == ID01) 
                {
                    return veh;
                }
            }

            return null;
                //return ID01;
        }

        /************************************************************************/
        /* 获取各个道路列表中最早到达的车辆,用于每次先进行判断的车辆，返回车辆的ID号                                                                     */
        /************************************************************************/
        private VehicleManager GetEarliestFromCSVehicle()
        {
            VehicleManager vtmp = null;
            VehicleManager SelTmp = null;
            float EarliestTime = 99999.0f;
            int ChosenCS = 0;       //标志所选中的CS号
            int ChosenVehi = 0;     //标志所选中车道中的车辆的ID号

            for (int i = 1; i < 5; ++i)
            {
                if (this.Token[i] == 0)   //为0则表示该资源空闲
                {
                    for (int j = 0; j < this.CS[i].Count; ++j)
                    {
                        vtmp = this.CS[i].ElementAt(j).Value;
                        string str = vtmp.getID();
                        //车辆已经经过该临界区
                        if ((vtmp.getTs() - Main.getGlobalTime()) <= 0.00000000001f)
                        {
                            Debug.Write("fdasdfdas");
                            continue;
                        }
                        if (Already_Authorized_All_CS_Vehicles.Contains(str))
                        {
                            //车辆的所有临界区已被授权
                            Debug.Write("fdasdfdas");
                            continue;
                        }
                        else
                        {
                            //车辆未被选中,则进行车辆的选择
                            if (vtmp.isSelect == false)
                            {
                                if ((EarliestTime - vtmp.getTs()) > 0.00000000001f)
                                {
                                    ChosenCS = i;
                                    ChosenVehi = j;
                                    EarliestTime = vtmp.getTs();
                                    SelTmp = vtmp;
                                }
                            }
                        }
                    }
                }
                else
                {

                }
            }
            if (SelTmp != null)
            {
                this.CS[ChosenCS].ElementAt(ChosenVehi).Value.isSelect = true;
            }
            return SelTmp;
        }

        /************************************************************************/
        /* 检验在道路消息队列组中的某一辆车是否，判断一辆是否是按照临界区先后循序进行申请的，返回true则非法                                                                     */
        /************************************************************************/
        private bool isTokenSequenceIllegal(int LaneID, string ID, int AuthCSID, ref string RepID)
        {
            SuperVehicleManager svm = null;
            int d = 0;

            //获取道路消息队列组中需要进行判断的车辆的总消息
            for (int i = 0; i < this.LaneQueue[LaneID].Count; i++)
            {
                if (this.LaneQueue[LaneID].ElementAt(i).ID == ID)
                {
                    svm = this.LaneQueue[LaneID].ElementAt(i);
                    break;
                }
            }

            if (svm != null)
            {
                //获取当前需要判断的临界区，即将要处理的临界区
                for (int i = 0; i < svm.CS_Count; i++)
                {
                    if (svm.VehicleManagers[int.Parse(svm.SectionID[i].ToString())] == null)
                    {
                        System.Windows.Forms.MessageBox.Show("error,isTokenSequenceIllegal1");
                        continue;
                    }
                    if (int.Parse(svm.SectionID[i].ToString()) == AuthCSID)
                    {
                        d = i;                          //若只需要一个临界区，则d=0；
                        break;
                    }
                }

                for (int i = 0; i < d; i++)
                {
                    //消息按照临界区序号进行存储
                    if (svm.VehicleManagers[int.Parse(svm.SectionID[i].ToString())] == null)
                    {
                        System.Windows.Forms.MessageBox.Show("error,isTokenSequenceIllegal2");
                        continue;
                    }
                    //车辆的所申请临界区之前的临界区已经申请完成，且所申请临界区该临界区还未申请成功，此时则说明合法
                    if (svm.VehicleManagers[int.Parse(svm.SectionID[i].ToString())].HasToken == false)
                    {
                        //                        Debug.WriteLine("Illegal \t" + ID + "\t" + AuthCSID + "\t" + svm.SectionID);
                        RepID = ID;
                        return true;
                    }
                }
            }
            else
            {
                //test
                Debug.WriteLine("fjkafds FIFO MQ 2307");
                //test finish
            }
            return false;
        }

        /************************************************************************/
        /* 检验当前授权车辆是否是道路中的第一辆车,若是首车，则返回true                                                                     */
        /************************************************************************/
        private bool isFirstVehicleInLane(int LaneID, string ID, int CSID)
        {
            SuperVehicleManager ktmp;
            string scs = null;
            int k = 0;
            int k2 = 1;
            //找到正在判断的车辆
            foreach (SuperVehicleManager kvp in LaneQueue[LaneID])
            {
                if (kvp.ID == ID)
                {
                    ktmp = kvp;
                    scs = ktmp.Original_SectionID;
                    break;
                }
                ++k;
            }
            //正在判断中车辆所申请临界区在其所用临界区中所处的位置
            for (int i = 0; i < scs.Length; ++i)
            {
                if (CSID != int.Parse(scs[i].ToString()))
                {
                    ++k2;
                }
                else
                {
                    break;
                }
            }
            //判断是否是首车
            bool mark = true;   //若是首车，则mark为true
            for (int i = 0; i < k; ++i)   //遍历申请车辆之前的所有车
            {
                for (int j = 0; j < k2; ++j)  //遍历包含所申请临界区之前的所有临界区
                {
                    string pre_scs = LaneQueue[LaneID].ElementAt(i).Original_SectionID;
                    if (pre_scs.Contains(scs[j].ToString()) == true)//前车包含本车所要申请的临界区，此时需判断前车是否已经离开该临界区
                    {
                        if (LaneQueue[LaneID].ElementAt(i).Left[CSID] == true)  //前车已离开该临界区，本车已可申请该临界区
                        {

                        }
                        else
                        {
                            mark = false;
                        }
                    }
                    else    //前车未包含本车所要申请的临界区，此时无需判断前车是否已经离开该临界区
                    {

                    }
                }
            }

            if (mark == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /************************************************************************/
        /* 检测资源是否出现环路，若返回true，则产生了回路 
         * 1、若该临界区被走过，则说明产生了回路
         * 2、若未被走过，则判断其所需的下一临界区
         */
        /************************************************************************/
        private bool dfsCheckCircuit(int current)
        {
            if (Walked[current])
            {
                return true;
            }
            Walked[current] = true;
            for (int i = 1; i <= 4; i++)
            {
                if (this.SourceGraph[current, i])
                {
                    //若箭头存在，即该临界区需求下一临界区
                    //则继续判断该临界区是否会出现回路
                    if (dfsCheckCircuit(i))
                    {
                        return true;
                    }
                }
            }
            Walked[current] = false;
            return false;
        }

        /************************************************************************/
        /* 判断是否会出现死锁，返回True则死锁产生    
         * 此时SQ.Count 表示临界区被授权的个数，而count表示各个临界区被授权车辆个数的总和
             key     Value
         *    0       234
         *            242
         *    1       356
         *            423       
         */
        /************************************************************************/
        private bool isTokenSequenceDeadLock(Dictionary<int, List<string>> SQ)
        {
            int i, j;
            int Count = 0;
            int[] array = new int[5];

            for (i = 0; i < 5; i++)
            {
                for (j = 0; j < 5; j++)
                {
                    this.SourceGraph[i, j] = false;
                }
                this.Walked[i] = false;
            }

            //先计算出SQ 中被授权车辆个数的总和  Count
            for (int Key = 0; Key < SQ.Count; Key++)
            {
                int ListIndex = 0;
                for (; ListIndex < SQ.Values.ElementAt(Key).Count; Count++, ListIndex++)
                {

                }
            }
            SuperVehicleManager[] svm = new SuperVehicleManager[Count];

            int xiabiao = 0;                                                     //svm数组中的 下标
            //获取待授权的所有车辆的车辆superManager信息，存入svm中
            for (int Key = 0; Key < SQ.Count; Key++)                             //对应到每一个临界区
            {
                int ListIndex = 0;
                for (; ListIndex < SQ.Values.ElementAt(Key).Count && xiabiao < Count; ListIndex++)        //每一个临界区 所对应的 授权车辆 队列
                {

                    string VehicleID = SQ.ElementAt(Key).Value[ListIndex]; //车辆ID
                    Vehicle VehicleTemp = FindVehicleByID(VehicleID);      //车辆对象
                    string LaneIDTemp = VehicleTemp.Get_Current_LaneID();  //车辆所在LaneID


                    for (j = 0; j < this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].Count; j++)
                    {
                        if (this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].ElementAt(j).ID == SQ.ElementAt(Key).Value[ListIndex])   //每一辆车 需要对应到一个lanequeue队列 找到它
                        {
                            svm[xiabiao] = this.LaneQueue[int.Parse(LaneIDTemp.ElementAt(5).ToString())].ElementAt(j);
                            xiabiao++;
                            break;
                        }
                    }
                }
            }

            //构建资源分配表
            for (i = 0; (i + 3) < 7; ++i)
            {//临界区标号
                for (j = 0; j < Count; j++)
                {//车辆数目
                    if (int.Parse(svm[j].SectionID[i].ToString()) != 0)
                    {
                        if (svm[j].Left[int.Parse(svm[j].SectionID[i].ToString())] == false)
                        {//若该临界区未走过，则将其下面要走的路径标志为true
                            if (int.Parse(svm[j].SectionID[i + 1].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i].ToString()), int.Parse(svm[j].SectionID[i + 1].ToString())] = true;
                            }
                            if (int.Parse(svm[j].SectionID[i + 2].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i + 1].ToString()), int.Parse(svm[j].SectionID[i + 2].ToString())] = true;
                            }
                            if (int.Parse(svm[j].SectionID[i + 3].ToString()) != 0)
                            {
                                this.SourceGraph[int.Parse(svm[j].SectionID[i + 2].ToString()), int.Parse(svm[j].SectionID[i + 3].ToString())] = true;
                            }
                        }
                        else
                        {//如果车辆已离开该临界区则无需在将临界区加入继续判断是否会死锁
                            /*                            Debug.WriteLine("fdasfsd");*/
                        }
                    }
                    else
                    {//若车辆为经过该临界区

                    }
                }
            }

            //检查是否有回路出现
            for (i = 1; i <= 4; i++)
            {
                //从第一个临界区开始检测，通过递归的方式，检测其所需要的临界区是否被走过，
                //若走过，那么就会出现环路
                if (dfsCheckCircuit(i))
                {
                    return true;
                }
            }
            return false;
        }

        /************************************************************************/
        /* 当临界区授权情况改变时，包括新授权和授权收回的情况，输出此时占用临界区的车辆，全局时间等信息。                                                                     */
        /************************************************************************/
        private void OutPutAuthMsg(int mark, Message msg)
        {

        }

        //Test 测试函数
        //private void TsetRecordMessageInformation(Message m) 
        //{
        //    string text = System.IO.File.ReadAllText(@"D:\IOTest\IOTest2.txt");
        //    text += m.GetSender() + " " + m.GetLaneID() + " " + m.GetReceiver() + " " + m.GetSectionID() + "\r\n";            
        //    System.IO.File.WriteAllText(@"D:\IOTest\IOTest2.txt", text);
        //}

        /************************************************************************/
        /* 发送临界区授权信息            ID为车辆ID                                                           */
        /************************************************************************/
        private void sendMessage(int Type, String ID, int Priority, int CSID, Intersection Intersection)
        {
            this.MsgCount++;
            float[] ts = new float[5];
            float[] te = new float[5];
            switch (Type)
            {
                case Definitions.MsgAuthorize:
                    Message m = new Message(Definitions.MsgAuthorize, Intersection.GetID(), ID,
                            ts, te, -1.0f, Priority, CSID.ToString(), -1,"");  //""站位使用
                                        

                    //写到消息队列
                    List<Message> AtoV_BufferTemp = Intersection.GetAtoV_Buffer();
                    AtoV_BufferTemp.Add(m);
                    Intersection.SetAtoV_Buffer(AtoV_BufferTemp);
                    MainData.UpdateIntersectionList(Intersection);

                    //MsgBuffer.AtoV_Buffer.Enqueue(m);
                    this.Token[CSID]++;
                    //this.OutPutAuthMsg(1, m);
                    break;
                case Definitions.MsgRefuse:
                    break;
                default:
                    //System.Windows.Forms.MessageBox.Show("Message Type is wrong ---- " + Type, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    System.Windows.Forms.MessageBox.Show("Error FIFO-MQ 2493");
                    return;
            }
            float time = Main.getGlobalTime() + Main.TimeStep;

        }

        /************************************************************************/
        /* 设置授权信息，TokenID为被授权的临界区号，ID是被授权车辆                                                                     */
        /************************************************************************/
        private void setToken(int TokenID, string ID)
        {
            //返回ID信息不够，返回车辆Vehicle对象  xc
            Vehicle Vehicle = FindVehicleByID(ID);
            string LaneID = Vehicle.Get_Current_LaneID();


            int j = 0;
            for (j = 0; j < this.LaneQueue[int.Parse(LaneID[5].ToString())].Count; j++)
            {
                if (this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).ID == ID)
                {
                    //LaneQueue中存储的信息

                    this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).HaveTokenCount++;
                    this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).Token[TokenID] = true;
                    this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).VehicleManagers[TokenID].HasToken = true;
                    for (int i = 0; i < 5; i++)
                    {
                        if (this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).VehicleManagers[i] != null)
                        {
                            this.LaneQueue[int.Parse(LaneID[5].ToString())].ElementAt(j).VehicleManagers[i].Token[TokenID] = true;
                        }
                    }
                }
            }

            //CS中存储的信息
            foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[TokenID])
            {
                if (kvp.Key == ID)
                {
                    kvp.Value.HasToken = true;
                    kvp.Value.Token[TokenID] = true;
                }
            }
            for (int i = 0; i < 5; ++i)
            {
                foreach (KeyValuePair<string, VehicleManager> kvp in this.CS[i])
                {
                    if (kvp.Key == ID)
                    {
                        kvp.Value.Token[TokenID] = true;
                    }
                }
            }
            return;
        }

        /************************************************************************/
        /* 判断各临界区的申请队列是否为空                                                                     */
        /************************************************************************/
        private bool IsCSEmpty()
        {
            bool mark = true;
            for (int i = 1; i < 5; ++i)
            {
                if (this.CS[i].Count != 0)
                {
                    mark = false;
                }
            }
            return mark;
        }

        /************************************************************************/
        /* 把已经全部授权车辆所需临界区的 车辆增加在 Already_Authorized_All_CS_Vehicles                                                                  */
        /************************************************************************/
        private void AddCarInAuthList(SuperVehicleManager svmp)
        {
            if (svmp.HaveTokenCount == svmp.CS_Count)
            {
                if (!this.Already_Authorized_All_CS_Vehicles.Contains(svmp.ID))
                {
                    this.Already_Authorized_All_CS_Vehicles.Add((svmp.ID));
                }
            }
        }

        //获取授权信息
        public Dictionary<int, List<string>> GetAuthorize_CS_to_Vehicle()
        {
            return this.Authorize_CS_to_Vehicle;
        }

        //根据ID在全局的VehicleList中找到Vehicle
        public static Vehicle FindVehicleByID(string ID)
        {
            Vehicle Vehicle = new Vehicle();
            for (int i = 0; i < MainData.Map.GlobalVehicleList.Count(); i++)
            {
                Vehicle veh = MainData.Map.GlobalVehicleList[i];
                if (veh.Get_ID() == ID)
                {
                    Vehicle = veh;
                }
            }
            return Vehicle;
        }


    }


}
